/*
	MIDAS Context Based Routing
	cbr_address.cc
	Copyright (c) 2007 Radoslaw Olgierd Schoeneich
	Copyright (c) 2007 Bartlomiej Zolnierkiewicz
	MEAG IT PW
*/

#include "cbr_address.h"
#include "cbr_crt.h"
#include "cbr_debug.h"

using namespace std;

/**
 * CBR Context Address constructor.
 *
 * @param a string describing context address
 */

cbr_ContextAddress::cbr_ContextAddress(const std::string& a)
{
	string::size_type i = 0, j = 0;

	while (j != std::string::npos) {
		j = a.find('&', i);
		std::string c = a.substr(i, j - i);
		concepts_set.insert((cbr_Concept) c);
		if (j != std::string::npos)
			i = j + 1;
	}
}

/**
 * Get CBR Context Address as a CBR triples list.
 *
 * @param src CBR id of the source node
 *
 * Traverses list of concepts belonging to CBR Context Address
 * and creates CBR triples list where each entry is:
 *
 * concept, hope count (== 0), CBR id of the source node
 *
 * @return CBR triples list for a given CBR id.
 */

cbr_TriplesList cbr_ContextAddress::getAsTriples(const cbr_ID& src) const
{
	cbr_ConceptsSet::const_iterator i;
	cbr_TriplesList list;

	for (i = concepts_set.begin(); i != concepts_set.end(); i++)
		list.push_back(new cbr_Triple(*i, 0, src));

	return list;
}

/**
 * Get CBR Context Address as a string.
 *
 * Traverses list of concepts belonging to CBR Context Address
 * and creates string out of them.
 *
 * @return CBR triples list for a given CBR id.
 */

std::string cbr_ContextAddress::getAsString() const
{
	string str;
	cbr_ConceptsSet::const_iterator i;

	for (i = concepts_set.begin(); i != concepts_set.end(); i++) {
		str.append(*i);
		str.append("&");
	}
	str.erase(str.length() - 1);

	return str;
}

/**
 * Match CBR Context Address to a given concept.
 *
 * @param concept concept to match CBR Context Address with
 *
 * @return "true" if the concept matches CBR Context Address.
 */

bool cbr_ContextAddress::matches(const cbr_Concept& concept) const
{
	return (concepts_set.find(concept) != concepts_set.end());
}

/**
 * Gets local Context Based Address.
 *
 * @param id local CBR id
 */

cbr_ContextAddress * cbr_getLocalCBA(cbr_ID id)
{
	string ctx;

	(void)cbr_getCtxDesc(id, ctx);

	return new cbr_ContextAddress(ctx.c_str());
}
